package com.dony.statistic.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dony.common.utils.price.ExchangeRateUtils;
import com.dony.order.domain.Order;
import com.dony.order.service.IOrderService;
import com.dony.statistic.domain.OrderDailySale;
import com.dony.statistic.mapper.OrderDailySaleMapper;
import com.dony.statistic.service.IOrderDailySaleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

/**
 * 订单Service业务层处理
 *
 * @author dony
 * @date 2022-09-07
 */
@Slf4j
@Service("OrderDailySaleService")
public class OrderDailySaleServiceImpl extends ServiceImpl<OrderDailySaleMapper, OrderDailySale> implements IOrderDailySaleService {


    @Resource
    private ExchangeRateUtils rateUtils;

    @Resource
    IOrderService orderService;

    /**
     * 同步最近一周的数据
     */
    @Override
    public void syncDailyOrderData(Long deptId) {
        LocalDate now = LocalDate.now();
        List<OrderDailySale> sales = new ArrayList<>();
        for (int i = 0; i < 31; i++) {
            QueryWrapper<Order> wrapper = new QueryWrapper<>();
            wrapper.between("create_time", now.minusDays(i + 1), now.minusDays(i));
            wrapper.select("order_sn", "income", "create_time", "total_amount", "currency")
                    .notIn("order_status", "UNPAID", "IN_CANCEL", "CANCELLED", "TO_RETURN");
            wrapper.eq("tenant_id", deptId);
            List<Order> orders = orderService.list(wrapper);
//            if (orders == null || orders.size() == 0) {
//                continue;
//            }
            //查询库中的数据
            QueryWrapper<OrderDailySale> dailySaleQueryWrapper = new QueryWrapper<OrderDailySale>();
            dailySaleQueryWrapper.eq("date", now.minusDays(i + 1));
            dailySaleQueryWrapper.eq("tenant_id", deptId);
            OrderDailySale dailySale = this.getOne(dailySaleQueryWrapper);
            if (dailySale == null) {
                dailySale = new OrderDailySale();
                dailySale.setDate(now.minusDays(i + 1));
                dailySale.setTenantId(deptId);
            }
            dailySale.setOrderNum((long) orders.size());
            dailySale.setSaleAmount(getTotalSalesAmount(orders));
            sales.add(dailySale);
        }
        this.saveOrUpdateBatch(sales);
    }


    /**
     * 获取今日销量
     */
    private float getTotalSalesAmount(List<Order> todayOrders) {
        //获取今日销量
        float totalSalesAmount = 0f;
        for (Order order : todayOrders) {
            if (order == null) continue;
            //计算人民币价格
            if (order.getIncome() != null) {
                totalSalesAmount += rateUtils.getRMBPriceFloat(order.getCurrency(), order.getIncome());
            } else if (order.getTotalAmount() != null) {
                totalSalesAmount += rateUtils.getRMBPriceFloat(order.getCurrency(), order.getTotalAmount());
            } else {
                log.error("订单总价异常无收入！订单号：{}", order.getOrderSn());
            }
        }
        return totalSalesAmount;
    }

}
